<template>
  <div class="page-container">
    <page-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <card title="基本信息">
        <page-form-row :gutter="24">
          <page-form-item field="templateName" required label="模板名称">
            <i-input
              v-model="form.templateName"
              placeholder="请输入"
              :max-length="20"
              :disabled="form.isSysTemplate !== 1 && route.params.id"
            />
          </page-form-item>
          <page-form-item field="contractType" required label="合同类型">
            <a-select
              :disabled="form.isSysTemplate !== 1 && !!route.params.id"
              v-model="form.contractType"
              placeholder="请选择"
              allow-clear
              :options="dict.contractTypeEnum"
              @change="onContractChange"
            />
          </page-form-item>
          <page-form-item field="clientType" required label="客户类型">
            <a-select
              v-model="form.clientType"
              placeholder="请选择"
              allow-clear
              :options="dict.clientTypeEnum"
              :disabled="form.isSysTemplate !== 1 && !!route.params.id"
              @change="handleChangeClientType"
            />
          </page-form-item>
        </page-form-row>
        <page-form-row :gutter="24">
          <page-form-item field="templateState" required label="状态">
            <a-select
              v-model="form.templateState"
              placeholder="请选择"
              allow-clear
              :options="dict.templateStateEnum"
              :disabled="form.isSysTemplate !== 1 && !!route.params.id"
            />
          </page-form-item>
          <page-form-item label="备注" size="2/3">
            <a-textarea v-model="form.remark" placeholder="请输入" :max-length="200" show-word-limit />
          </page-form-item>
        </page-form-row>
      </card>
      <card title="模板文件" :showDivider="false">
        <page-form-row :gutter="24">
          <page-form-item field="companySealFileId" required label="公司公章" size="1">
            <div>
              <div class="upload-desc">普通版的电子合同将会以此公司印章作为签章的依据，付费版的不会使用此印章。</div>
              <upload-ocr v-model="form.companySealFileId" types="PNG" />
              <div class="upload-desc">请上传png格式，背景为透明的印章图</div>
            </div>
          </page-form-item>
        </page-form-row>
        <page-form-row :gutter="24">
          <page-form-item required label="模板制作方式" size="1">
            <a-radio-group v-model="form.makeType">
              <a-radio :value="1">
                在线编辑
                <a-tooltip content="支持在富文本编辑器中自定义配置，需要使用系统中存在的变量进行配置">
                  <icon-question-circle size="16" />
                </a-tooltip>
              </a-radio>
            </a-radio-group>
          </page-form-item>
        </page-form-row>
        <page-form-row :gutter="24">
          <page-form-item field="contractContent" size="1">
            <div class="editor-box">
              <div class="peditor-box">
                <PEditor :id="form.id" :value="form.contractContent" @input="onPEditorInput" :clientType="form.clientType" />
              </div>
            </div>
          </page-form-item>
        </page-form-row>
      </card>
    </page-form>
    <page-form-footer :ok-loading="okLoading" @ok="submitFn" />
  </div>
</template>

<script setup name="ContractTemplateForm">
  import { onMounted, ref, h } from 'vue'
  import PEditor from '../components/PEditor.vue'
  import { usePageDict } from '@/hooks/useDict'
  import { addContractTemplate, getContractDetail, editContractTemplate } from '@/api/business/contract'
  import useNavigate from '@/hooks/useNavigate'
  import { useRoute } from 'vue-router'
  import { Modal } from '@arco-design/web-vue'

  const { navigateBack } = useNavigate()
  const dict = usePageDict('contractPageData')

  const route = useRoute()

  const okLoading = ref(false)
  const formRef = ref()
  const form = ref({
    makeType: 1,
    templateState: 0,
    orderType: route.query.orderType,
  })

  const validateContractContent = (value, callback) => {
    if (!value) {
      callback('请输入')
    } else if (value.trim() === '') {
      callback('请输入')
    } else {
      callback()
    }
  }

  const rules = {
    templateName: [{ required: true, message: '请输入', trigger: 'blur' }],
    contractType: [{ required: true, message: '请输入', trigger: 'blur' }],
    clientType: [{ required: true, message: '请输入', trigger: 'blur' }],
    templateState: [{ required: true, message: '请输入', trigger: 'blur' }],
    contractContent: [{ required: true, validator: validateContractContent, trigger: 'change' }],
    companySealFileId: [{ required: true, message: '请上传', trigger: 'change' }],
  }

  const onPEditorInput = (value) => {
    if (value.trim() !== '') {
      form.value.contractContent = value
    } else {
      form.value.contractContent = ''
    }
  }

  const typeName = ref('')
  const onContractChange = (value) => {
    dict.contractTypeEnum.forEach((item) => {
      if (item.value === value) {
        typeName.value = item.label
      }
    })
  }

  const submitFn = () => {
    formRef.value.validate((valid) => {
      if (!valid) {
        okLoading.value = true
        if (route.params.id) {
          editContractTemplate(form.value)
            .then((res) => {
              console.log(res, 'res')
              okLoading.value = false
              navigateBack()
            })
            .finally(() => {
              okLoading.value = false
            })
        } else {
          addContractTemplate(form.value)
            .then((res) => {
              console.log(res, 'res')
              okLoading.value = false
              navigateBack()
            })
            .finally(() => {
              okLoading.value = false
            })
        }
      }
    })
  }

  const getContractDetailFn = () => {
    getContractDetail({ id: route.params.id }).then((res) => {
      console.log(res, 'res')
      form.value = res.result
      console.log(form.value, 'form.value')
    })
  }

  const handleChangeClientType = (e) => {
    console.log('e', form.value.contractContent)
    if (e == 2) {
      // 个人
      if (form.value.contractContent) {
        const text = form.value.contractContent
        // 匹配富文本编辑器中的参数
        const condition = [
          '<var class="mceNonEditable">企业客户名称</var>',
          '<var class="mceNonEditable">负责人电话</var>',
          '<var class="mceNonEditable">纳税人识别号</var>',
        ]
        // 展示参数
        const template = ['企业客户名称', '负责人电话', '纳税人识别号']
        let temp = []
        condition.forEach((item, index) => {
          if (text.includes(item)) {
            temp.push(template[index])
          }
        })
        if (temp.length) {
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            content: h('div', {}, [
              h('span', {}, '富文本编辑器中存在参数'),
              h('span', { style: { color: '#165dff' } }, temp.join('、')),
              h('span', {}, '，客户类型切换为个人会员后将清除上述参数，请再次确认是否切换客户类型？'),
            ]),
            onOk: () => {
              form.value.clientType = 2
              const contractContent = form.value.contractContent.replace(
                /<var\s+class="(["mceNonEditable"]+)">(['企业客户名称','负责人电话','纳税人识别号']+)<\/var>/g,
                ''
              )
              form.value.contractContent = contractContent
            },
            onCancel: () => {
              form.value.clientType = 1
            },
          })
        }
      }
    }
  }

  onMounted(() => {
    if (route.params.id) {
      getContractDetailFn()
    }
  })
</script>

<style lang="less" scoped>
  .page-container {
    .editor-box {
      display: flex;

      .use-help-box {
        width: 340px;
        height: 413px;
        overflow: hidden;
        border: 1px solid #f2f3f5;

        .help-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-left: 12px;
          width: 340px;
          height: 40px;
          background: #f2f3f5;
          color: #1d2129;
          font-size: 14px;
          font-weight: 600;

          .help-header-button {
            padding-right: 12px;
            height: 100%;
          }
        }

        .help-body {
          height: 372px;
          overflow-y: auto;
          padding: 12px 12px;
          font-size: 14px;
          font-weight: 400;
          color: #1d2129;

          &-header {
            margin-bottom: 8px;
          }

          &-item {
            &-title {
              font-weight: 500;
            }

            &-content {
              font-size: 12px;
              color: #86909c;
            }
          }
        }
      }
    }

    .upload-desc {
      font-size: 14px;
      color: #86909c;
      line-height: 22px;
      margin: 6px 0;
      &:first-child {
        margin-top: 0;
      }
    }
  }
</style>
